from django.shortcuts import render
import os

from django.conf import settings
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.core.files.storage import default_storage
from django.core.files.base import ContentFile
import json
from .models import User
from rest_framework_simplejwt.tokens import RefreshToken
# Create your views here.


@csrf_exempt
def upload_avatar(request):
    if request.method == 'POST':
        avatar = request.FILES.get('avatar')
        if not avatar:
            return JsonResponse({'error': '没有收到头像文件'}, status=400)

        # 保存头像到服务器
        avatar_name = default_storage.save(f'avatars/{avatar.name}', ContentFile(avatar.read()))
        avatar_url = f'{settings.MEDIA_URL}{avatar_name}'

        return JsonResponse({'url': avatar_url}, status=201)
    return JsonResponse({'error': '无效的请求'}, status=405)

# 生成 JWT Token 的函数
def get_tokens_for_user(user):
    refresh = RefreshToken.for_user(user)
    return {
        'refresh': str(refresh),
        'access': str(refresh.access_token),
    }

@csrf_exempt
def register(request):
    if request.method == 'POST':
        try:
            data = json.loads(request.body)
            username = data.get('username')
            password = data.get('password')
            avatar_url = data.get('avatarUrl')

            if not username or not password or not avatar_url:
                return JsonResponse({'error': '请提供完整信息'}, status=400)

            if User.objects.filter(username=username).exists():
                return JsonResponse({'error': '用户名已存在'}, status=400)

            # 保存用户信息到数据库
            user = User.objects.create(username=username, password=password, avatar_url=avatar_url)
            # 生成 JWT Token
            tokens = get_tokens_for_user(user)

            # 返回 userId 和 JWT Token
            return JsonResponse({
                'message': '注册成功',
                'userId': user.id,
                'token': tokens['access'],  # 返回 access token
                'refresh': tokens['refresh']  # 返回 refresh token
            }, status=201)

        except json.JSONDecodeError:
            return JsonResponse({'error': '请求数据格式错误'}, status=400)

    return JsonResponse({'error': '无效的请求方法'}, status=405)
